<template>
  <div class="app-main-box" v-if="$route.path === '/transportOrderManagement/railway'">
    <!-- 铁路运单页面 -->
    <div v-show="activePage == 'first'">
      <div class="func-btn">
        <el-dropdown popper-class="dropDownStyle" :teleported="false" type="primary" style="margin-right: 12px;"
          @command="handleCommand">
          <!-- 导入数据 -->
          <el-button-group>
            <el-button type="primary">导入数据</el-button>
            <el-button type="primary" icon="ArrowDown" style="width: 32px;"></el-button>
          </el-button-group>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="multiply_important">批量导入</el-dropdown-item>
              <el-dropdown-item command="history_important">历史导入</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 搜索区域 -->
      <el-form class="global-search-form" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="from-item" label="磅单号：" prop="weightBillNo" style="width: 260px;">
          <el-input v-noSpace v-model="queryParams.weightBillNo" placeholder="请输入磅单号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item class="from-item" label="箱号：" prop="containerNo">
          <el-input v-noSpace v-model="queryParams.containerNo" placeholder="请输入箱号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item class="from-item" label="运单号：" prop="waybillNo">
          <el-input v-noSpace v-model="queryParams.waybillNo" placeholder="请输入运单号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item class="from-item" label="车号：" prop="trainNo">
          <el-input v-noSpace v-model="queryParams.trainNo" placeholder="请输入车号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item class="from-item" label="装车日期：" style="min-width: max-content;width: 504px">
          <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" placement="right" :teleported="false"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button class="global-search-button" type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button class="global-search-button" icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <div class="global-table-container">
        <el-table class="global-border-radius-table" algin="center" v-loading="loading" :data="transportList">
          <el-table-column label="磅单号" prop="weightBillNo" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column label="车号" prop="trainNo" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="箱号" prop="containerNo" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="篷布号" prop="coverClothNo" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="运单号" prop="waybillNo" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column label="货物" prop="cargo" min-width="100" :show-overflow-tooltip="true" />
          <el-table-column label="重量(吨)" prop="weight" min-width="100" :show-overflow-tooltip="true" />
          <el-table-column label="装车日期" prop="loadingDate" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="发站" prop="departureStation" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="到站" prop="arrivalStation" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="托运人" prop="consignor" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column label="收货人" prop="consignee" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column label="导入人" prop="creatorName" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="导入时间" prop="createTime" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column fixed="right" label="操作" class-name="small-padding" min-width="240">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="openDialog(scope.row)">编辑</el-button>
              <el-button link :type="scope.row.originatingId ? 'primary' : 'info'" icon="View"
                @click="handleView(scope.row)">发端数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 导入文件对话框（已废弃） -->

      <!-- 编辑铁路运单对话框 -->
      <el-dialog title="编辑运单" v-model="dialog_form_edit" width="800px" style="min-width: 750px" append-to-body>
        <!-- 编辑表单区域 -->
        <!-- 提示 -->
        <el-form-item v-if="formEdit.originatingId" class="global-tip-container" style="width: 100%;">
          <div class="global-tip">
            <span class="tip-icon"><svg-icon icon-class="light-tip" /></span>
            <div class="tip-content">
              <p>当前运单已完成发端数据匹配，无法修改箱号以及装货日期.</p>
            </div>
          </div>
        </el-form-item>
        <el-form class="global-form-edit" :model="formEdit" ref="formEditRef" :rules="formEditRules"
          label-width="120px">
          <el-form-item label="磅单号：" prop="weightBillNo" class="form-items">
            <el-input v-noSpace v-model="formEdit.weightBillNo" class="form-input" placeholder="请输入磅单号"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="车号：" prop="trainNo" class="form-items">
            <el-input v-noSpace v-model="formEdit.trainNo" class="form-input" placeholder="请输入车号" clearable></el-input>
          </el-form-item>
          <el-form-item label="箱号：" prop="containerNo" class="form-items">
            <el-input v-noSpace v-model="formEdit.containerNo" class="form-input" placeholder="请输入箱号" clearable
              :disabled="formEdit.originatingId ? true : false"></el-input>
          </el-form-item>
          <el-form-item label="篷布号：" prop="coverClothNo" class="form-items">
            <el-input v-noSpace v-model="formEdit.coverClothNo" class="form-input" placeholder="请输入篷布号"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="运单号：" prop="waybillNo" class="form-items">
            <el-input v-noSpace v-model="formEdit.waybillNo" class="form-input" placeholder="请输入运单号"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="货物：" prop="cargo" class="form-items">
            <el-input v-noSpace v-model="formEdit.cargo" class="form-input" placeholder="请输入货物" clearable></el-input>
          </el-form-item>
          <el-form-item label="重量(吨)：" prop="weight" class="form-items">
            <el-input v-noSpace v-model="formEdit.weight" class="form-input" placeholder="请输入重量" clearable>
              <template #append>吨</template>
            </el-input>
          </el-form-item>
          <el-form-item label="装车日期：" prop="loadingDate" class="form-items">
            <el-date-picker value-format="YYYY-MM-DD" v-model="formEdit.loadingDate" type="date" placeholder="请选择装车日期"
              style="width: 100%;" clearable :disabled="formEdit.originatingId ? true : false" />
          </el-form-item>
          <el-form-item label="发站：" prop="departureStation" class="form-items">
            <el-input v-noSpace v-model="formEdit.departureStation" class="form-input" placeholder="请输入发站"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="到站：" prop="arrivalStation" class="form-items">
            <el-input v-noSpace v-model="formEdit.arrivalStation" class="form-input" placeholder="请输入到站" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="托运人：" prop="consignor" class="form-items">
            <el-input v-noSpace v-model="formEdit.consignor" class="form-input" placeholder="请输入托运人"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="收货人：" prop="consignee" class="form-items">
            <el-input v-model="formEdit.consignee" class="form-input" placeholder="请输入收货人" clearable></el-input>
          </el-form-item>
        </el-form>

        <div class="dialog-footer" style="margin-top: 2px;">
          <el-button type="primary" @click="submitFormEdit">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 页码控件 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize" :pageSizes="[15, 20, 30, 50]" @pagination="getList" />
    </div>

    <!-- 对账页面 -->
    <div v-show="activePage == 'second'" class="page-second-container">
      <el-page-header class="page-head" @back="activePage = 'first'">
        <template #content>
          <span class="text-large font-600 mr-3"> 导入数据 </span>
        </template>
      </el-page-header>

      <!-- 1：铁路数据 -->
      <div class="modal-content">
        <el-checkbox v-model="checked_rail" label="铁路数据" size="large" disabled />
        <div class="form-content">
          <!-- case1:已选择文件 -->
          <div v-if="fileList.length" class="preview-file-content">
            <div class="left">
              <svg-icon :icon-class="getExtension(current_file.name)" style="width: 100%;height: 100%;" />
            </div>
            <div class="file-info">
              <div class="file-name">{{ current_file.name }}</div>
              <span v-if="current_file.size / 1024 > 1024" class="file-size">{{ (current_file.size / 1024 /
                1024).toFixed(2) }}MB</span>
              <span v-else class="file-size">{{ (current_file.size / 1024).toFixed(2) }}KB</span>
            </div>
            <div class="right">
              <div class="preview-file" @click="handlePreview">
                <el-icon>
                  <View />
                </el-icon>
              </div>
              <div class="delete-file" @click="removeFileList">
                <el-icon>
                  <Close />
                </el-icon>
              </div>
            </div>
          </div>
          <!-- case2:未选择文件 -->
          <div v-if="!fileList.length" class="select-file">
            <div class="select-file-content">
              <el-upload class="upload-demo" accept=".csv, .xls, .xlsx" :on-change="handleChange" :auto-upload="false"
                :multiple="false">
                <!-- (未上传)点按钮选取文件 -->
                <el-button type="primary">选择文件</el-button>
              </el-upload>
              <el-button link type="primary" icon="download" @click="downloadTemplate">下载导入模板</el-button>
            </div>
            <div class="select-file-tip">支持格式.xlsx，.xls，csv，文件大小不得大于5M，最多支持导入2000条数据</div>
          </div>

          <!-- case1:导入表格数据有误 -->
          <div class="upload-fail" v-if="errorList.length">
            <div class="instructment-tip">表格中存在错误,具体错误如下,请检查后重新导入...</div>
            <div class="upload-fail-table">
              <div class="infinite-list-wrapper">
                <ul class="list">
                  <li v-for="i in errorList" :key="i.rowIndex" class="list-item">{{ `第${i.rowIndex}行，${i.errorMsg}` }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <!-- case2:导入表格数据有重复 -->
          <div class="upload-fail" v-if="duplicateData.length">
            <div class="instructment-tip">表格中有重复数据，以下为重复数据，请检查后重新导入</div>
            <div class="upload-fail-table" style="height: auto">
              <el-table class="global-border-radius-table" algin="center" :data="duplicateData" style="font-size: 12px;"
                max-height="282px">
                <!-- 磅单号 车号 篷布号 运单号 货物名称 重量 发站 到站 发货人 收货人 装车日期 -->
                <el-table-column label="磅单号" prop="weightBillNo" min-width="180" :show-overflow-tooltip="true" />
                <el-table-column label="箱号" prop="containerNo" min-width="120" :show-overflow-tooltip="true" />
                <el-table-column label="车号" prop="trainNo" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="篷布号" prop="coverClothNo" min-width="120" :show-overflow-tooltip="true" />
                <el-table-column label="运单号" prop="waybillNo" min-width="120" :show-overflow-tooltip="true" />
                <el-table-column label="货物名称" prop="cargo" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="重量(吨)" prop="weight" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="发站" prop="departureStation" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="到站" prop="arrivalStation" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="发货人" prop="consignor" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="收货人" prop="consignee" min-width="100" :show-overflow-tooltip="true" />
                <el-table-column label="装车日期" prop="loadingDate" min-width="150" :show-overflow-tooltip="true" />
              </el-table>
            </div>
          </div>
          <!-- case3:导入表格中重复数据文案 -->
          <div class="upload-fail" v-if="errorCode == 'DuplicateRailwayData' && !duplicateData.length">
            <div class="instructment-tip">表格中存在错误,具体错误如下,请检查后重新导入...</div>
            <div class="upload-fail-table">
              <div class="infinite-list-wrapper">
                <p style="text-align: left;color: #333;">{{ duplicate_content }}</p>
              </div>
            </div>
          </div>

        </div>
      </div>

      <div class="divider"></div>

      <!-- 2：发端数据 -->
      <div class="modal-content">
        <el-checkbox v-model="checked_start" label="发端数据" size="large" disabled />
        <div class="form-content">
          <el-form ref="formStartRef" :model="formStart" :rules="formStartRule">
            <el-form-item>
              <el-radio-group v-model="radio_start" @change="changeStartRadio">
                <el-radio label="0" value="0">智能匹配</el-radio>
                <el-radio label="1" value="1">按日期选择</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="form-item" prop="routeIds">
              <template #label>
                <div class="label-wrap">
                  <span class="label-text">线路</span>
                  <span class="label-single">：</span>
                </div>
              </template>
              <el-select v-model="formStart.routeIds" placeholder="请选择线路" filterable multiple :teleported="false"
                style="width: 100%;" clearable>
                <el-option v-for="item in routeOption" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item prop="dateRange_start" v-if="radio_start == 1" class="form-item">
              <template #label>
                <div class="label-wrap">
                  <span class="label-text">发车日期</span>
                  <span class="label-single">：</span>
                </div>
              </template>
              <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="formStart.dateRange_start"
                type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :teleported="false"></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 文件预览传送门 -->
      <teleport to="body">
        <div class="global-preview-file-container" v-if="show_frame_view">
          <div v-loading="render_loading" element-loading-text="数据加载中..." style="width: 60%; height: 80%">
            <!-- <IFrame :src="file_url"></IFrame> -->
            <VueOfficeExcel :src="file_url" @rendered="rendered" style="width: 100%; height: 100%"></VueOfficeExcel>
          </div>
          <span class="global-viewer-close" @click="closePreviewFile">
            <el-icon>
              <Close />
            </el-icon>
          </span>
        </div>
      </teleport>

      <!-- 开始匹配 -->
      <div class="footer" style="display: flex;justify-content: left; padding-bottom: 30px">
        <el-button type="primary" @click="handleMatchSubmit" :loading="match_loading">匹配数据</el-button>
      </div>
    </div>

    <!-- 匹配结果表格页面 -->
    <div v-show="activePage == 'third'" class="page-third-container" v-loading="match_loading">
      <el-page-header class="page-head" @back="activePage = 'second'" style="padding: 0 24px;">
        <template #content>
          <span class="text-large font-600 mr-3"> 导入数据 </span>
        </template>
      </el-page-header>

      <!-- 有未完全匹配数据 -->
      <!-- v-if="waybillUnmatchedData.length" -->
      <div class="match-data-container" v-if="waybillUnmatchedData.length">
        <div class="title-bar-container" style="padding: 0 24px;">
          <div class="global-title-bar">
            <div class="dot"></div>
            <div class="text">未成功匹配数据</div>
          </div>
          <el-popover popper-class="custom-popper" placement="right" title="未成功匹配说明" :width="400" trigger="hover"
            :content="waybillUnmatchedContent">
            <template #reference>
              <el-icon>
                <InfoFilled />
              </el-icon>
            </template>
          </el-popover>
        </div>
        <div class="global-table-container" style="margin-top: 20px;">
          <vxe-table border align="center" show-overflow max-height="215" highlight-hover-row
            :row-config="{ height: 35 }" :scroll-y="{ enabled: true, gt: 0 }" :scroll-x="{ enabled: true, gt: 0 }"
            :data="waybillUnmatchedData" :header-cell-style="grayColor">
            <!-- 车牌号 磅单号 箱号  过磅日期   -->
            <vxe-column type="seq" width="70"></vxe-column>
            <!-- 磅单号 车号 箱号 运单号  发站 到站 装车日期 -->
            <vxe-colgroup title="铁路" header-class-name="middle-front">
              <vxe-column title="磅单号" field="railwayWeightBillNo" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="箱号" field="railwayContainerNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="车号" field="railwayTrainNo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="篷布号" field="railwayCoverClothNo" min-width="110"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="运单号" field="railwayBillNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="货物名称" field="railwayCargo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="重量" field="railwayWeight" min-width="80" header-class-name="middle-front"></vxe-column>
              <vxe-column title="发站" field="railwayDepartureStation" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="到站" field="railwayArrivalStation" min-width="100" header-class-name="middle-front">
              </vxe-column>
              <vxe-column title="发货人" field="railwayConsignor" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="收货人" field="railwayConsignee" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="装车日期" field="railwayLoadingDate" min-width="100"
                header-class-name="middle-front"></vxe-column>
            </vxe-colgroup>
            <!-- 车牌号 车辆来源 磅单号 箱号 线路 货物 发车时间 -->
            <vxe-colgroup title="发端" header-class-name="start-front">
              <vxe-column title="车牌号" field="originatingPlateNo" min-width="100"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="磅单号" field="originatingWeightBillNo" min-width="180"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="箱号" field="originatingContainerNo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="线路名称" field="originatingRouteName" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="货物" field="originatingCargo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="发车时间" field="originatingDepartureTime" min-width="150"
                header-class-name="start-front"></vxe-column>
            </vxe-colgroup>
          </vxe-table>
        </div>
      </div>

      <!-- 有重复匹配数据 -->
      <!-- v-if="waybillDuplicatedData.length" -->
      <div class="match-data-container" v-if="waybillDuplicatedData.length">
        <div class="title-bar-container" style="padding: 0 24px;">
          <div class="global-title-bar">
            <div class="dot"></div>
            <div class="text">重复匹配数据</div>
          </div>
          <el-popover popper-class="custom-popper" placement="right" title="重复匹配说明" :width="400" trigger="hover"
            :content="waybillDuplicatedContent">
            <template #reference>
              <el-icon>
                <InfoFilled />
              </el-icon>
            </template>
          </el-popover>
        </div>

        <div class="global-table-container" style="margin-top: 20px;">
          <vxe-table border align="center" show-overflow max-height="215" :row-config="{ height: 35 }"
            :data="waybillDuplicatedData" :header-cell-style="grayColor" :mergeCells="mergeRules">
            <!-- 车牌号 磅单号 箱号  过磅日期   -->
            <vxe-column type="seq" width="70"></vxe-column>
            <!-- 磅单号 车号 箱号 运单号  发站 到站 装车日期 -->
            <vxe-colgroup title="铁路" header-class-name="middle-front">
              <vxe-column title="磅单号" field="railwayWeightBillNo" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="箱号" field="railwayContainerNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="车号" field="railwayTrainNo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="篷布号" field="railwayCoverClothNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="运单号" field="railwayBillNo" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="货物名称" field="railwayCargo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="重量" field="railwayWeight" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="发站" field="railwayDepartureStation" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="到站" field="railwayArrivalStation" min-width="100" header-class-name="middle-front">
              </vxe-column>
              <vxe-column title="发货人" field="railwayConsignor" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="收货人" field="railwayConsignee" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="装车日期" field="railwayLoadingDate" min-width="150"
                header-class-name="middle-front"></vxe-column>
            </vxe-colgroup>
            <!-- 车牌号 车辆来源 磅单号 箱号 线路 货物 发车时间 -->
            <vxe-colgroup title="发端" header-class-name="start-front">
              <vxe-column title="车牌号" field="originatingPlateNo" min-width="100"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="磅单号" field="originatingWeightBillNo" min-width="180"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="箱号" field="originatingContainerNo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="线路名称" field="originatingRouteName" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="货物" field="originatingCargo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="发车时间" field="originatingDepartureTime" min-width="150"
                header-class-name="start-front"></vxe-column>
            </vxe-colgroup>
          </vxe-table>
        </div>
      </div>

      <!-- 匹配结果 -->
      <div class="match-data-container" v-if="resultData.length">
        <div class="flex-space-between" style="padding: 0 24px;">
          <div class="global-title-bar">
            <div class="dot"></div>
            <div class="text">匹配结果</div>
          </div>
          <div class="flex-right">
            <el-button round type="default" plain style="margin-bottom: 20px" icon="Download"
              @click="exportMatchData">导出数据</el-button>
          </div>
        </div>
        <div class="global-table-container" style="margin-top: 20px;">
          <vxe-table border align="center" show-overflow max-height="605" highlight-hover-row
            :row-config="{ height: 35 }" :scroll-y="{ enabled: true, gt: 0 }" :scroll-x="{ enabled: true, gt: 0 }"
            :data="resultData" :header-cell-style="grayColor">
            <!-- 车牌号 磅单号 箱号  过磅日期   -->
            <vxe-column type="seq" width="70"></vxe-column>
            <!-- 磅单号 车号 箱号 运单号  发站 到站 装车日期 -->
            <vxe-colgroup title="铁路" header-class-name="middle-front">
              <vxe-column title="磅单号" field="railwayWeightBillNo" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="箱号" field="railwayContainerNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="车号" field="railwayTrainNo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="篷布号" field="railwayCoverClothNo" min-width="120"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="运单号" field="railwayBillNo" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="货物名称" field="railwayCargo" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="重量" field="railwayWeight" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="发站" field="railwayDepartureStation" min-width="100"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="到站" field="railwayArrivalStation" min-width="100" header-class-name="middle-front">
              </vxe-column>
              <vxe-column title="发货人" field="railwayConsignor" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="收货人" field="railwayConsignee" min-width="180"
                header-class-name="middle-front"></vxe-column>
              <vxe-column title="装车日期" field="railwayLoadingDate" min-width="150"
                header-class-name="middle-front"></vxe-column>
            </vxe-colgroup>
            <!-- 车牌号 车辆来源 磅单号 箱号 线路 货物 发车时间 -->
            <vxe-colgroup title="发端" header-class-name="start-front">
              <vxe-column title="车牌号" field="originatingPlateNo" min-width="100"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="磅单号" field="originatingWeightBillNo" min-width="180"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="箱号" field="originatingContainerNo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="线路名称" field="originatingRouteName" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="货物" field="originatingCargo" min-width="120"
                header-class-name="start-front"></vxe-column>
              <vxe-column title="发车时间" field="originatingDepartureTime" min-width="150"
                header-class-name="start-front"></vxe-column>
            </vxe-colgroup>
          </vxe-table>
        </div>
      </div>

      <div class="match-data-footer">
        <div class="btn-list">
          <el-button type="default" @click="handleSubmitAgain" :loading="match_loading">重新匹配</el-button>
          <el-button type="primary" @click="importMatchData" :loading="import_loading">导入数据</el-button>
        </div>
      </div>
    </div>

    <!-- 发端数据-查看运单对话框 -->
    <start-info ref="formViewRef"></start-info>

    <!-- 匹配成功页面 -->
    <div class="page-fourth-container" v-if="activePage == 'fourth'">
      <el-icon :size="70" color="#00b42a">
        <SuccessFilled />
      </el-icon>
      <span class="operate-title">操作成功</span>
      <span class="operate-text">本次任务共导入{{ importRecord.dataAmount }}条数据，您可以通过点击查看详情按钮和下载按钮分别查看导入详情和下载数据匹配结果</span>
      <div class="btn-list">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handelDownLoad">下载</el-button>
        <el-button type="primary" @click="handelViewInfo">查看详情</el-button>
      </div>
    </div>
  </div>

  <router-view v-else></router-view>
</template>

<script setup name="transportOrderList">
import * as XLSX from 'xlsx';
import IFrame from '@/components/iFrame'
import { ElMessage } from 'element-plus'
import { getListApi, importFileApi, updateListApi, matchDataApi, importMatchDataApi, exportExcleApi, exportMatchDataApi } from "@/api/transportOrderManagement/railway";
import { reactive, ref, onBeforeMount, onBeforeUnmount, } from 'vue';
import startInfo from '@/views/components/startInfo'
import { getRouteSimpleListApi } from "@/api/common";
import useCommonStore from '@/store/modules/railCommon'
const router = useRouter();
const { proxy } = getCurrentInstance();
let routeOption = ref([])  // 线路下拉列表
let formViewRef = ref(null)
let dialog_form_edit = ref(false); // 铁路运单编辑
let loading = ref(true);
let match_loading = ref(false) // 开始匹配loading
let render_loading = ref(false) // 文件渲染loading
let import_loading = ref(false)
let total = ref(0);
let title = ref("");
let dateRange = ref([]);
let transportList = reactive([]) // 发端短驳
let checked_rail = ref(true)
let checked_start = ref(true)
let show_frame_view = ref(false) // 文件预览
const waybillUnmatchedContent = ref(`
在数据匹配过程中，我们会将铁路数据与发端数据进行匹配。 
匹配的标准是：磅单号与箱号都相同。如果铁路数据成功匹配到发端对应数据，则视为匹配成功。如果未匹配到发端数据则视为匹配失败。 
主要原因可能是发端数据缺失或磅单号、箱号错误等原因，请检查和处理后重新匹配。
  `)
const waybillDuplicatedContent = ref(`
  在数据匹配过程中，我们会将铁路数据与发端数据进行匹配。
  匹配的标准是：磅单号与箱号都相同。如出现同一条铁路数据匹配到多条发端数据，则视为重复匹配。 
  主要原因可能是发端数据缺失或磅单号、箱号错误等原因，请检查和处理后重新匹配。
`)
// 需要存储的状态
let activePage = ref('first')
let radio_start = ref("0") // 发端：0-智能匹配，1-日期
let current_file = ref({})
let fileList = ref([])
let file_url = ref('') // 文件预览地址
let errorList = ref([])
let errorCode = ref('')
let duplicateData = ref([])  // 导入出错重复数据
let waybillUnmatchedData = ref([]) // 未匹配到的数据
let waybillDuplicatedData = ref([]) // 匹配重复数据
let resultData = ref([]) // 匹配结果
let matchId = ref('')
let importRecord = ref({}) // 导入数据成功后的导入记录
let mergeRules = ref([])
/** 列表查询参数 */
const data = reactive({
  formEdit: {},
  formStart: {
    routeIds: []
  },
  formEditRules: {
    weightBillNo: [{ required: true, message: "磅单号不能为空", trigger: "blur" }],
    trainNo: [{ required: true, message: "车号不能为空", trigger: "blur" }],
    coverClothNo: [{ required: true, message: "篷布号不能为空", trigger: "blur" }],
    waybillNo: [{ required: true, message: "运单号不能为空", trigger: "blur" }],
    cargo: [{ required: true, message: "货物不能为空", trigger: "blur" }],
    weight: [
      { required: true, message: "重量不能为空", trigger: "blur" },
      { pattern: /^(?!0(\.0+)?$)\d+(\.\d+)?$/, message: '仅允许输入大于0的小数和整数', trigger: 'blur' },
      { pattern: /^(?!0\d)(\d+(\.\d*)?|\.\d+)$/, message: '输入内容不合法', trigger: 'blur' }
    ],
    loadingDate: [{ required: true, message: "装车日期不能为空", trigger: "blur" }],
    arrivalStation: [{ required: true, message: "发站不能为空", trigger: "blur" }],
    departureStation: [{ required: true, message: "到站不能为空", trigger: "blur" }],
    consignor: [{ required: true, message: "托运人不能为空", trigger: "blur" }],
    consignee: [{ required: true, message: "收货人不能为空", trigger: "blur" }],
    containerNo: [
      { required: true, message: "箱号不能为空", trigger: "blur" }
    ]
  },
  formStartRule: {
    routeIds: [{ required: true, message: '请选择线路', trigger: 'change' }],
    dateRange_start: [{ required: true, message: '请选择发车日期', trigger: 'change' }]
  },
  queryParams: {
    pageIndex: 1,
    pageSize: 15,
  }
});
const { queryParams, formEdit, formStart, formEditRules, formStartRule } = toRefs(data);
/** 复杂表头样式 */
const grayColor = ({ column }) => {
  if (column.headerClassName == 'start-front') {
    return {
      backgroundColor: '#f2f4f7 !important',
      color: '#515a6e',
      textAlign: 'center',
      height: '40px !important'
    }
  }
  else {
    return {
      backgroundColor: '#e1f3d8 !important',
      color: '#515a6e',
      textAlign: 'center',
      height: '40px !important'
    }
  }
}

onBeforeMount(() => {
  getPageState()
})

/** 在此周期中管理状态 */
onBeforeUnmount(() => {
  let initiate_reconciliation = {
    radio_start: radio_start.value, // 发端（0-智能匹配，1-时间选择）
    activePage: activePage.value,
    current_file: current_file.value, // 选择完后本地文件对象
    fileList: fileList.value, // 选择的文件列表，
    file_url: file_url.value, // 预览文件使用文件url
    show_frame_view: show_frame_view.value, // 显示文件预览条件
    formStart: formStart.value,
    errorList: errorList.value,
    errorCode: errorCode.value,
    duplicateData: duplicateData.value,
    waybillUnmatchedData: waybillUnmatchedData.value,
    waybillDuplicatedData: waybillDuplicatedData.value, // 发端时间区间
    resultData: resultData.value,
    matchId: matchId.value,
    importRecord: importRecord.value,
    mergeRules: mergeRules.value
  }
  writeData(initiate_reconciliation)
})

/** 写入数据 */
async function writeData(data) {
  const res = await useCommonStore().setCommonData(data)
  console.log(res, '写入铁路对账数据');
}

/** 定义一个默认主动执行函数获取当前页面的状态 */
async function getPageState() {
  let result = await useCommonStore().getCommonData()
  radio_start.value = result.radio_start // 发端单选
  activePage.value = result.activePage
  current_file.value = result.current_file // 选择的文件列表，
  fileList.value = result.fileList // 选择的文件列表，
  file_url.value = result.file_url // 预览文件使用文件url
  show_frame_view.value = result.show_frame_view // 显示文件预览条件
  formStart.value = result.formStart
  errorList.value = result.errorList
  errorCode.value = result.errorCode
  duplicateData.value = result.duplicateData
  waybillUnmatchedData.value = result.waybillUnmatchedData
  waybillDuplicatedData.value = result.waybillDuplicatedData // 发端时间区间
  resultData.value = result.resultData
  matchId.value = result.matchId
  importRecord.value = result.importRecord
  mergeRules.value = result.mergeRules
}

/** 
* Methods
*/
/** 导入指令事件 */
function handleCommand(command) {
  switch (command) {
    case 'multiply_important': activePage.value = 'second'; break;
    case 'history_important': router.push('/transportOrderManagement/historyRecord');
  }
}

/** 打开编辑对话框 */
async function openDialog(row) {
  // 打开时重置表单
  resetEditForm()
  formEdit.value = { ...row }
  dialog_form_edit.value = true;
};

/** 打开详情页面对话框 */
function handleView(row) {
  if (!row.originatingId) {
    ElMessage({ message: '未完成发端数据匹配', type: 'error' })
    return false
  }
  formViewRef.value.viewData(row)
}

/** 提交表单 */
function submitFormEdit() {
  proxy.$refs["formEditRef"].validate(valid => {
    if (valid) {
      updateList()
    }
  })
}

/** 提交编辑铁路运单列表表单 */
function updateList() {
  let row = { ...formEdit.value, railwayConsignmentId: formEdit.value.id }
  updateListApi(row).then(response => {
    if (response.code === 1) {
      updateTableRowData(response.data)
      dialog_form_edit.value = false
      ElMessage({ message: '操作成功', type: 'success' })
    } else {
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
  })
}

/** 手动更新表格中某行的数据 */
function updateTableRowData(params) {
  transportList = transportList.map(item => {
    if (item.id.toString() == params.id.toString()) {
      item = Object.assign(item, params)
    }
    return item
  });
}

/** 编辑运单对话框-取消按钮 */
function cancelEdit() {
  dialog_form_edit.value = false;
  resetEditForm();
}

/** 重置编辑运单对话框 */
function resetEditForm() {
  formEdit.value = {
    weightBillNo: undefined,
    trainNo: undefined,
    containerNo: undefined,
    coverClothNo: undefined,
    waybillNo: undefined,
    cargo: undefined,
    weight: undefined,
    loadingDate: undefined,
    arrivalStation: undefined,
    departureStation: undefined,
    consignor: undefined,
    consignee: undefined
  }
  proxy.resetForm("formEditRef");
}

/** 查询发端短驳 */
function getList() {
  loading.value = true;
  const params = queryParams.value
  getListApi(proxy.addDateRange(params, dateRange.value, 'Date')).then(response => {
    if (response.code === 1) {
      transportList = response.data.records;
      total.value = Number(response.data.total);
      loading.value = false;
    } else {
      loading.value = false;
    }
  }).catch(err => {
    loading.value = false;
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageIndex = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/**
 * 
 * 关于对账页面相关方法
 * 
 */
/** 文件预览渲染完成 */
function rendered() {
  console.log('渲染完成');
  render_loading.value = false
}

/** 线路下拉列表 */
function getRouteSimpleList() {
  getRouteSimpleListApi().then(response => {
    if (response.code === 1) {
      routeOption.value = response.data
    } else {
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
  })
}

/** 发端数据复选框状态变化 */
function changeStartRadio(radio) {
  radio_start.value == radio
}

/** 到端数据文件状态变化 */
function handleChange(file) {
  removeFileList()
  let supposeType = ['xls', 'xlsx', 'csv']
  /** 获取文件后缀名 */
  let fileRaw = file.raw || file.file
  if (supposeType.includes(getExtension(fileRaw.name))) {
    current_file.value = file.raw || file.file
    // 将最新的文件加入到fileList中
    fileList.value = [current_file.value];
  } else {
    ElMessage({ message: '文件类型暂不支持，请重新上传', type: 'error', duration: 2000 })
  }
}

/** 获取文件后缀名 */
function getExtension(filename) {
  if (filename) {
    return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
  }
}

/** 关闭iframe文件预览按钮 */
function closePreviewFile() {
  render_loading.value = false
  show_frame_view.value = false
}

/** 预览文件 */
async function handlePreview() {
  render_loading.value = true
  show_frame_view.value = true
  console.log(current_file.value, '文件对象')
  if (current_file.value.type == 'application/vnd.ms-excel' || current_file.value.type == 'text/csv') {
    let binaryFile = await converXlsToXlsx(current_file.value)
    let base64_file = await getBase64(binaryFile)
    file_url.value = base64_file
  } else {
    let base64_file = await fileToBase64(current_file.value)
    file_url.value = base64_file
  }
}

/** File转Base64 */
async function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      resolve(event.target.result);
    };
    reader.readAsDataURL(file);
    reader.onerror = reject;
  });
}

// 二进制流转换为base64 格式。
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const blob = new Blob([file], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); // 必须指定type类型
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.readAsDataURL(blob);
    reader.onerror = (error) => reject(error);
  });
}

/** 文件格式转换 */
function converXlsToXlsx(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const xlsxBinary = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      resolve(xlsxBinary);
    }
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  })
}

/** 删除所选文件 */
function removeFileList() {
  current_file.value = {}
  file_url.value = ''
  fileList.value = [];
  errorList.value = []
  duplicateData.value = []
  errorCode.value = ''
}

/** 下载导入模板 */
function downloadTemplate() {
  const link = document.createElement('a');
  link.href = 'https://bituo-logistics-saas.oss-cn-beijing.aliyuncs.com/web/excel/template/%E9%93%81%E8%B7%AF%E6%95%B0%E6%8D%AE%E6%A8%A1%E6%9D%BF.xlsx'
  link.download = '铁路数据模板.xlsx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/** 开始匹配数据 */
function handleMatchSubmit() {
  if (!fileList.value.length) {
    ElMessage({ message: '未选择到端文件!,请选择文件再尝试匹配!', type: 'error', duration: 2000 })
  } else {
    matchData()
  }
}

/** 匹配数据接口 */
async function matchData() {
  const p1 = new Promise((resolve, reject) => {
    proxy.$refs['formStartRef'].validate(valid => {
      if (valid) {
        resolve()
      }
    })
  })
  Promise.all([p1]).then(async () => {
    match_loading.value = true
    // 判断
    const { dateRange_start, routeIds } = formStart.value
    let originating_params = proxy.addDateRange({ routeIds: routeIds }, dateRange_start, 'Time')
    const originating = new Blob([JSON.stringify(originating_params)], { type: 'application/json;charset=utf-8' });
    const routeId = new Blob([JSON.stringify(routeIds)], { type: 'application/json;charset=utf-8' });
    let formData = new FormData();
    // 铁路文件
    formData.append("railwayDataFile", current_file.value);
    // 发端数据
    formData.append('originating', originating);
    // 发端线路id
    formData.append('routeIds', routeId);
    await matchDataApi(formData).then((response) => {
      if (response.code === 1) {
        matchId.value = response.data.matchId
        resultData.value = response.data.waybillMatchData
        waybillUnmatchedData.value = response.data.waybillUnmatchedData
        // formGenerate.value.matchId = response.data.matchId
        // 测试数据
        // let mergeData = [
        //     {
        //       railwayWeightBillNo: '11',railwayContainerNo: '11',railwayTrainNo: '11',railwayCoverClothNo:'11',
        //       railwayBillNo: '11',railwayCargo: '11',railwayWeight: '11', railwayDepartureStation: '11',railwayArrivalStation: '11',
        //       railwayConsignor: '11', railwayConsignee: '11',railwayLoadingDate: '11',
        //       originatingId: null,originatingPlateNo: '',originatingWeightBillNo: '',originatingContainerNo: '',
        //       originatingRouteName: '',originatingCargo: '',originatingDepartureTime: ''
        //     },
        //     {
        //       railwayWeightBillNo: '11',railwayContainerNo: '11',railwayTrainNo: '11',railwayCoverClothNo:'11',
        //       railwayBillNo: '11',railwayCargo: '11',railwayWeight: '11', railwayDepartureStation: '11',railwayArrivalStation: '11',
        //       railwayConsignor: '11', railwayConsignee: '11',railwayLoadingDate: '11',
        //       originatingId: null,originatingPlateNo: '',originatingWeightBillNo: '',originatingContainerNo: '',
        //       originatingRouteName: '',originatingCargo: '',originatingDepartureTime: ''
        //     },

        //     {
        //       railwayWeightBillNo: '12',railwayContainerNo: '12',railwayTrainNo: '12',railwayCoverClothNo:'12',
        //       railwayBillNo: '12',railwayCargo: '12',railwayWeight: '12', railwayDepartureStation: '12',railwayArrivalStation: '12',
        //       railwayConsignor: '12', railwayConsignee: '12',railwayLoadingDate: '12',
        //       originatingId: 12,originatingPlateNo: '',originatingWeightBillNo: '',originatingContainerNo: '',
        //       originatingRouteName: '',originatingCargo: '',originatingDepartureTime: ''
        //     },
        //     {
        //       railwayWeightBillNo: '12',railwayContainerNo: '12',railwayTrainNo: '12',railwayCoverClothNo:'12',
        //       railwayBillNo: '12',railwayCargo: '12',railwayWeight: '12', railwayDepartureStation: '12',railwayArrivalStation: '12',
        //       railwayConsignor: '12', railwayConsignee: '12',railwayLoadingDate: '12',
        //       originatingId: 12,originatingPlateNo: '',originatingWeightBillNo: '',originatingContainerNo: '',
        //       originatingRouteName: '',originatingCargo: '',originatingDepartureTime: ''
        //     }
        //   ]
        /** 合并单元格 */
        let mergeData = response.data.waybillDuplicatedData
        let mergeByoriginatingId = []
        mergeByoriginatingId = mergeCellsByoriginatingId(mergeData, 1, 1, [])
        mergeRules.value = mergeCells(mergeData, 1, 1, []).concat(mergeByoriginatingId)
        // 先合并后赋值
        waybillDuplicatedData.value = mergeData

        // 条件判断
        // 1.关闭loading
        match_loading.value = false
        // 2.切换页面
        activePage.value = 'third'
        // 3.显示匹配结果数据
      } else {
        match_loading.value = false
        errorCode.value = response.errorCode
        switchErrorType(response)
      }
    }).catch(() => {
      match_loading.value = false
    })
  })
}


/** 递归函数合并铁路数据 */
function mergeCells(data, startRow = 1, rowSpan = 1, mergeCellRule = []) {
  // 1.如果数据为空，返回空数组
  if (!data.length) return [];
  // 获取当前行和下一行的数据
  const currentRow = data[startRow - 1];
  const nextRow = data[startRow];
  // 2.判断当前行和下一行是否相同
  const isSameRow = [
    'railwayWeightBillNo',
    'railwayContainerNo',
    'railwayTrainNo',
    'railwayCoverClothNo',
    'railwayBillNo',
    'railwayCargo',
    'railwayWeight',
    'railwayDepartureStation',
    'railwayArrivalStation',
    'railwayConsignor',
    'railwayConsignee',
    'railwayLoadingDate'
  ].every((key) => currentRow[key] == nextRow?.[key]);
  // 3.如果当前行和下一行相同，递归调用函数
  if (isSameRow) {
    return mergeCells(data, startRow + 1, rowSpan + 1, mergeCellRule);
  }
  // 4.如果当前行和下一行不同，将当前行的合并规则添加到 mergeCellRule 数组中
  else {
    if (rowSpan > 1) {
      mergeCellRule.push(
        { row: startRow - rowSpan, rowspan: rowSpan, col: 1, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 2, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 3, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 4, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 5, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 6, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 7, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 8, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 9, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 10, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 11, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 12, colSpan: 1 },
      );
    }
  }
  // 5.如果下一行存在，递归调用函数
  if (nextRow) {
    return mergeCells(data, startRow + 1, 1, mergeCellRule);
  }
  // 如果下一行不存在，返回 mergeCellRule 数组
  return mergeCellRule;
}

/** 递归函数合并发端数据 */
function mergeCellsByoriginatingId(data, startRow = 1, rowSpan = 1, mergeCellRule = []) {
  // 1.如果数据为空，返回空数组
  if (!data.length) return [];
  // 获取当前行和下一行的数据
  const currentRow = data[startRow - 1];
  const nextRow = data[startRow];
  // 2.判断当前行和下一行是否相同
  const isSameRow = ['originatingId',].every((key) => currentRow[key] === nextRow?.[key] && currentRow[key] !== null && nextRow?.[key] !== null);
  // 3.如果当前行和下一行相同，递归调用函数
  if (isSameRow) {
    return mergeCellsByoriginatingId(data, startRow + 1, rowSpan + 1, mergeCellRule);
  }
  // 4.如果当前行和下一行不同，将当前行的合并规则添加到 mergeCellRule 数组中
  else {
    if (rowSpan > 1) {
      mergeCellRule.push(
        { row: startRow - rowSpan, rowspan: rowSpan, col: 13, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 14, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 15, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 16, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 17, colSpan: 1 },
        { row: startRow - rowSpan, rowspan: rowSpan, col: 18, colSpan: 1 },
      );
    }
  }
  // 5.如果下一行存在，递归调用函数
  if (nextRow) {
    return mergeCellsByoriginatingId(data, startRow + 1, 1, mergeCellRule);
  }
  // 如果下一行不存在，返回 mergeCellRule 数组
  return mergeCellRule;
}

/** 匹配错误类型 */
function switchErrorType(result) {
  if (result.errorCode == 'FormDataError') {
    errorList.value = result.data
  }
  else if (result.errorCode == 'DuplicateRailwayData') {
    if (result.data) {
      duplicateData.value = result.data
    } else {
      duplicateData.value = []
      duplicate_content.value = `系统检测到您导入的Excel文件中存在重复数据。
      这些数据可能已经在之前的对账中被处理过，请检查文件内容，避免重复对账`
    }
  } else {
    ElMessage({ message: result.message, type: 'error', duration: 1500 })
  }
}

/** 重新匹配 */
async function handleSubmitAgain() {
  await matchData()
  // ElMessage({ message: '已为您进行重新匹配，请查看匹配结果!', type: 'success', duration: 2000 })
}

/** 导入匹配结果 */
function importMatchData() {
  if (waybillUnmatchedData.value.length) {
    ElMessage({ message: '有未匹配成功的数据，请检查后重试!', type: 'error', duration: 2000 })
  } else if (waybillDuplicatedData.value.length) {
    ElMessage({ message: '有重复匹配数据，请检查后重试!', type: 'error', duration: 2000 })
  } else {
    importData()
  }
}


/** 导入匹配结果接口 */
function importData() {
  import_loading.value = true
  importMatchDataApi({ matchId: matchId.value }).then((response) => {
    if (response.code === 1) {
      // 1.关闭loading
      import_loading.value = false
      // 2.打开成功页面
      activePage.value = 'fourth'
      importRecord.value = response.data
    } else {
      import_loading.value = false
      ElMessage({ message: response.message || '操作失败！', type: 'error', duration: 2000 })
    }
  }).catch(() => {
    import_loading.value = false
  })
}

/** 下载匹配成功的数据记录 */
function handelDownLoad() {
  exportExcle()
}

/** 下载匹配成功的数据接口 */
async function exportExcle() {
  let params = { importId: importRecord.value.id, includeOriginatingData: true }
  exportExcleApi(params).then((response) => {
    // const disposition = response.headers['content-disposition'];
    // const matchArray = disposition.match(/filename="(.*)"/);
    // const filename = matchArray[1];
    let filename = `铁路发端汇总_${getCurrentFormattedTime()}` + '.xlsx'
    const url = window.URL.createObjectURL(response);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click()
    document.body.removeChild(link); // 下载完成后移除元素
    window.URL.revokeObjectURL(url); // 释放URL对象
  })
}

/** 导出匹配结果 */
function exportMatchData() {
  exportResult()
}

/** 导出匹配结果接口 */
async function exportResult() {
  let params = {
    matchId: matchId.value
  }
  let filename = `铁路数据匹配结果_${getCurrentFormattedTime()}` + '.xlsx'
  exportMatchDataApi(params).then((response) => {
    const url = window.URL.createObjectURL(response);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click()
    document.body.removeChild(link); // 下载完成后移除元素
    window.URL.revokeObjectURL(url); // 释放URL对象
  })
}

/** 生成文件名 */
function getCurrentFormattedTime() {
  const now = new Date();
  // 获取年、月、日、时、分、秒
  const year = now.getFullYear();
  // getMonth() 返回 0-11，所以需要加1
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');

  // 构建格式化的字符串
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

/** 查看对账详情 */
function handelViewInfo() {
  let params = { ...importRecord.value }
  clearPage()
  router.push({
    path: '/transportOrderManagement/historyRecordInfo',
    query: {
      historyImportId: params.id,
      operatorName: params.operatorName,
      dataAmount: params.dataAmount,
      createTime: params.createTime
    }
  })
}

/** 成功之后返回 */
function goBack() {
  clearPage()
}

/** 清除页面所有状态 */
function clearPage() {
  radio_start.value = '0' // 发端
  activePage.value = 'first'
  current_file.value = {} // 选择完后本地文件对象
  fileList.value = [] // 选择的文件列表，
  file_url.value = '' // 预览文件使用文件url
  show_frame_view.value = false // 显示文件预览条件
  formStart.value = {}
  errorList.value = []
  errorCode.value = ''
  duplicateData.value = []
  waybillUnmatchedData.value = []
  waybillDuplicatedData.value = [] // 发端时间区间
  resultData.value = []
  matchId.value = ''
  importRecord.value = {}
}



getList();
getRouteSimpleList()
</script>

<style lang='scss' scoped>
@import '../../../assets/styles/variables.module.scss';

.app-main-box {
  background: #fff;
  border-radius: 12px;
  min-height: calc(100vh - 125px);
  width: calc(100% - 40px);

  /** 功能按钮 */
  .func-btn {
    padding: 24px 24px 0px;
  }


  :deep(.vxe-table-row) {
    height: 32px !important;
  }

  :deep(.el-checkbox.el-checkbox--large .el-checkbox__label) {
    font-size: 16px !important;
    font-weight: 500;
  }
}

:deep(.el-form-item__label) {
  height: 36px;
  text-align: center !important;
  line-height: 36px !important;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

// 自定义下拉菜单样式
:deep(.dropDownStyle) {
  width: 120px !important;
  position: absolute !important;
  left: 0px !important;
  font-size: 14px;
  font-style: normal;

  .el-dropdown-menu__item {
    width: 100%;
    justify-content: center;
  }
}

.page-head {
  height: 50px;
  display: inline-flex;
  align-items: flex-end;
}

.page-second-container {
  padding: 0 40px;
}

.divider {
  border-bottom: 2px dashed $--color-bg-info;
}

.modal-content {
  padding: 30px 0px;
}

.select-file-content {
  display: flex;
}

.select-file-tip {
  font-size: 14px;
  color: $--color-info;
  margin-top: 14px;
}

.form-content {
  .preview-file-content {
    width: 500px;
    height: 50px;
    border-radius: 4px;
    background-color: $--color-bg-info;
    display: flex;
    align-items: center;
    padding: 5px 14px;

    .left {
      width: 40px;
      height: 40px;
    }

    .file-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin-left: 14px;
      color: #333;

      .file-name {
        font-size: 14px;
      }

      .file-size {
        font-size: 12px;
        margin-top: 4px;
      }
    }

    .right {
      margin-left: 14px;
      display: flex;
      text-align: right;
      font-size: 22px;
      color: $--color-info;

      .delete-file {
        margin-left: 14px
      }

      .preview-file,
      .delete-file {
        cursor: pointer;
      }
    }
  }

  :deep(.el-form-item) {
    width: 528px !important;
  }
}

.label-wrap {
  display: flex;
  flex-wrap: nowrap;

  .label-text {
    height: 36px;
    text-align: justify;
    display: inline-block;
    width: 4em;
    color: #515a6e;
    font-weight: bold;

    &::after {
      display: inline-block;
      content: "-";
      width: 4em;
      opacity: 0;
    }
  }

  .label-single {
    width: max-content;
  }
}

:deep(.el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before) {
  content: "*";
  display: inline-block;
  width: 14px;
  height: 32px;
  text-align: center;
  line-height: 32px;
  color: $--color-danger;
  margin-right: 8px !important;
}

:deep(.el-upload-list) {
  display: none !important;
}

.trapezoid-box {
  width: 100% !important;
  display: flex !important;
  margin-bottom: 24px;
}

.upload-fail {
  margin-top: 20px;
}

.instructment-tip {
  font-size: 14px;
  // color: $--color-info;
  color: $--color-danger;
}

.upload-fail-table {
  width: 528px;
  height: 150px;
  margin-top: 10px;
  box-sizing: border-box;

  .infinite-list-wrapper {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    background-color: $--color-bg-info;
    padding: 0px 14px;
    overflow-y: auto;
  }

  .list {
    padding: 0;
    margin: 0;
    list-style: none;

    .list-item {
      display: flex;
      align-items: flex-end;
      height: 30px;
      line-height: 30px;
      font-size: 12px;
      color: $--color-danger;
      white-space: nowrap;
    }
  }

  .list-message-container {
    padding: 0;
    margin: 0;
    list-style: none;

    .list-message {
      text-align: left;
      color: $--color-danger;
    }
  }
}


/** 2.匹配结果页面样式 */
.title-bar-container {
  display: flex;
  align-items: center;

  .el-icon {
    color: $--color-warning;
    font-size: 24px;
    padding: 0 12px;
    cursor: pointer;
  }
}

.match-data-container {
  margin-top: 30px;
}

.match-data-footer {
  margin: 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 24px;
}

/** 3.匹配成功之后的页面 */
.page-fourth-container {
  width: 100%;
  height: calc(100vh - 135px);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  top: 20%;

  .operate-title {
    color: #333;
    font-weight: 500;
    font-size: 20px;
    margin: 20px 0px 20px;
  }

  .operate-text {
    max-width: 500px;
    text-wrap: wrap;
    white-space: wrap;
    text-align: center;
    line-height: 1.5;
    color: $--color-info;
    font-size: 16px;
  }

  .btn-list {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50px;

    .el-button {
      min-width: 100px;
      margin: 0 20px;
    }
  }
}

.flex-space-between {
  width: calc(100% - 48px) !important;
  display: flex;
  align-items: center;

  .flex-right {
    flex: 1;
    justify-self: flex-end !important;
    text-align: right;

    .el-button {
      margin: 0 !important;
    }
  }
}
</style>